$(function(){
    requestAjax();
    _gridInit();
    gridInit0m();
    $('li[data-opt="add"]').on('click', addBrands);
    $('li[data-opt="u_save"],button[data-opt="u_save"]').on('click',function(){
        //console.log($('#jgTable').jqGrid('getRowData'));
        var requestArr = [];
        _grid.jqGrid('getRowData').forEach(function(v,i,a){
            requestArr.push({'Code':v.Code,'Name':v.Name/*,'OrderId':i+1*/})
        });
        console.log(requestArr);
        var requestData = Object.create(postData);
        requestData.Method = 'U';
        requestData.Content = requestArr;
        $.ajax({
            type: "post",
            url: mdmPath+'/MDM0036/MDM003601',
            data: requestData,
            dataType: "json",
            success: function (re) {
                if (re.Status == 200) {
                    alert('保存成功');
                } else {
                    alert(re.Message);
                }
            }
        });
    });
    //$('.modal-data').draggable({distance:20/*, delay:500*/});
    $('.modal-data').draggable({ /*revert: true*/ /*, helper: "clone"*/ });
});

var _grid = $('#jgTable'),
    grid0m = $('#jgTable0m');
var _Data = [];

var postData0m = {
    Method: 'Q',
    Content: {
        Putaway: 'Y',
        SearchText: ''
    }
}
for(i in postData){
    postData0m[i] = postData[i];
}

function requestAjax(){
    var _postData = Object.create(postData);
    _postData.Method = 'Q';
    _postData.Content = {
        SearchText: '' 
    };
    _postData.page = 1;
    _postData.rows = 100;
    //_postData.sidx = 'OrderId';
    _postData.sidx = 'Code';
    _postData.sord = 'Asc'

    var url = mdmPath + '/MDM0036/MDM003602';
    $.ajax({
        async: false,
        type: "post",
        url: url,
        data: _postData,
        dataType: "json",
        success: function (re) {
            if (re.Status == 200) {
                loadAjax(re);
            } else if (re.Status == -999) {
                alert_QX($('body'), re.Message);
            }  else {
                alert(re.Message);
            }
        }
    });
}
function loadAjax(re){
    if(re.Content){
        _Data = re.Content.rows;
    }
}

function alarmFormatter(cellvalue, options, rowdata){
    var grid = $(this);
    if(JSON.stringify(rowdata)!=='{}'){
        cellvalue = '<a href="javascript:0" opt-data="'+grid[0].id+'_delete" title="删除"><i class="fa fa-trash-o"></i></a>';
    }else{
        cellvalue = '';
    }
    return cellvalue;
}
function _gridInit(){
    var _gridData = Object.create(gridData);
    _gridData.datatype = "local";
    _gridData.rowNum = 100;
    _gridData.colModel = [
        {label:'代码', name:'Code', sortable:false, width:60},
        {label:'名称', name:'Name', sortable:false},
        // {label:'创建时间', name:'CreateDate', sortable:false},
        {label:'创建用户', name:'CreateUser', width:60, sortable:false},
        // {label:'更新时间', name:'UpdateDate', sortable:false},
        {label:'更新用户', name:'UpdateUser', width:60, sortable:false},
        {label:'操作', name:'Options', align:'center', width:60, formatter: alarmFormatter, sortable:false}
    ];
    _gridData.beforeRequest = function(){
        _gridData.grid.jqGrid("setGridParam", {
            data : _Data
        });
    };
    _gridData.loadComplete = function(xhr){ 
        var rowData = _gridData.grid.jqGrid("getRowData");
        $('a[opt-data="jgTable_delete"]').unbind('click').bind('click',function(){
            var rowId = $(this).parent().parent()[0].id;
            _gridData.grid.jqGrid("delRowData",rowId);
            _Data.forEach(function(v,i,a){
                v.Code===rowData[rowId-1].Code&&_Data.splice(i,1);
            });
            //console.log(_Data)
        });
        // _gridData.grid.jqGrid('sortableRows',{
        //     update:function(ev,ui){
        //         var item = ui.item[0],
        //         ri = item.rowIndex,
        //         itemId = item.id;
        //     }
        // });
    };
    gridInit(_gridData);
}
function gridInit0m(){

    var gridData0m = Object.create(gridData);
    gridData0m.grid = $('#jgTable0m');
    gridData0m.pager = $('#jgPager0m');
    gridData0m.url = mdmPath + '/MDM0004/MDM000402';
    gridData0m.height = '390px';
    gridData0m.colModel = [
        {label:'代码', name:'Code', sortable:false},
        {label:'名称', name:'Name'}
    ];
    gridData0m.sortname = 'Name';
    gridData0m.beforeRequest = function(){
        gridData0m.grid.jqGrid("setGridParam", {
            postData : postData0m,
        });
    };
    gridData0m.loadComplete = function(xhr){
        $("li[data-opt='opt_search']").find(">i").unbind('click').bind('click', function () {
            postData.Content.SearchText = $("#opt_search").find(">input").val();
            gridData0m.grid.trigger("reloadGrid");
        });
        Search();
    }
    gridData0m.multiselect = true;
    gridInit(gridData0m);
}

function addBrands(){
    $('.modal-overlay').removeClass('hidden');
    $('#addBtn').unbind('click').bind('click', function(){
        addSubmit();
    });
    gridSize();
}

function Search(){
    $("li[data-opt='opt_search']").find(">.fa-search").unbind('click').bind('click', function(){
        var Category3 = $('input[data-id="Category3"]').val();
        var Code = $('input[data-id="Code"]').val();
        var ProductName = $('input[data-id="ProductName"]').val();
        postData0m.Content = {
            Category3: Category3,
            Code: Code,
            SearchText: ProductName
        }
        grid0m.jqGrid("clearGridData").trigger("reloadGrid");
    });
}

function addSubmit(){
    // console.log('提交按钮');
    var rowIds = grid0m.jqGrid('getGridParam', 'selarrrow');
    for(var arr=[],i=0;i<rowIds.length;i++){
        var addRowData = grid0m.jqGrid("getRowData",rowIds[i]);	//这是获得 某一行的数据
        // var strValue= grid.jqGrid("getCell",rowIds[i],"Code");	//获得单元格的值
        _Data.push(addRowData);
    }
    _Data = _Data.unique('Code');
    _grid.jqGrid("clearGridData").trigger("reloadGrid");
    myModal.addClass('hidden');
}

var _gridWidth = $('.u_toolbar');
var gridWidth0m = $('.u_modal_body');
function gridSize(){ 
    _grid.setGridWidth(_gridWidth.width());
    grid0m.setGridWidth(gridWidth0m.width());
}